package com.yilei.testninegridview

import android.content.ContentResolver
import android.net.Uri
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.viewModelScope
import com.obs.services.ObsClient
import com.obs.services.exception.ObsException
import com.obs.services.model.HttpMethodEnum
import com.obs.services.model.Multipart
import com.obs.services.model.PutObjectRequest
import com.obs.services.model.TemporarySignatureRequest
import com.yilei.testninegridview.MyUtils.launch
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.IOException

class MainViewModel:BaseViewModel() {
    val result=MutableLiveData<String>()
    fun newUpLoad(name:String,FILE_PATH: Uri,contentResolver: ContentResolver){
       launch {
            val AK = "0OKWE5DLGUZI7ZJO5SA1" // 替换为您的AK
            val SK = "iEr8cjx0QP8dxxKvDu17CWiPBzYA7M6NlSsc8pZa" // 替换为您的SK
            val ENDPOINT = "obs.cn-north-4.myhuaweicloud.com" // 替换为您的OBS Endpoint
            val BUCKET_NAME = "pictures-6ab5" // 替换为您的存储桶名称
            val obsClient = ObsClient(AK, SK, ENDPOINT)
            try {
//            val file = FILE_PATH
//            val inputStream = FileInputStream(file)
                val scope = CoroutineScope(Dispatchers.Default)
                //fun asyncTask() {
                    val inputStream=contentResolver.openInputStream(FILE_PATH)
                    val putObjectRequest = PutObjectRequest(BUCKET_NAME, name, inputStream)
                    val putObjectResult = obsClient.putObject(putObjectRequest)

                    result.postValue(putObjectResult.objectKey)

                //}
//                scope.launch {
//                    asyncTask()
//                }

                // println("Uploaded file with UUID: ${putObjectResult.uploadId}")
            } catch (e: ObsException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {
                try {
                    obsClient.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }
    val getUrlResult=MutableLiveData<String>()
    fun getUrl(objectKey:String) {

        val AK = "0OKWE5DLGUZI7ZJO5SA1" // 替换为您的AK
        val SK = "iEr8cjx0QP8dxxKvDu17CWiPBzYA7M6NlSsc8pZa" // 替换为您的SK
        val ENDPOINT = "obs.cn-north-4.myhuaweicloud.com" // 替换为您的OBS Endpoint
        val BUCKET_NAME = "pictures-6ab5" // 替换为您的存储桶名称
        val obsClient = ObsClient(AK, SK, ENDPOINT)

        // URL有效期，3600秒
        val expireSeconds = 3600L


        val request = TemporarySignatureRequest(HttpMethodEnum.GET, expireSeconds)
        request.bucketName = "pictures-6ab5"
        request.objectKey = objectKey

        val response = obsClient.createTemporarySignature(request)

        Log.i("CreateTemporarySignature", "Getting object using temporary signature url:")
        Log.i("CreateTemporarySignature", "\t" + response.signedUrl)
        getUrlResult.postValue(response.signedUrl)
        //imageUrls.add(response.signedUrl)

//        val builder: Request.Builder = Request.Builder()
//        for ((key, value) in response.actualSignedRequestHeaders) {
//            builder.header(key, value)
//        }
//
//
////使用GET请求下载对象
//        val httpRequest: Request = builder.url(response.signedUrl).get().build()
//        val httpClient = OkHttpClient.Builder()
//            .followRedirects(false) // 禁止自动重定向
//            .retryOnConnectionFailure(false) // 连接失败时不重试
//            .cache(null) // 不使用缓存（或者可以设置一个有效的 Cache 对象）
//            .build() // 构建 OkHttpClient 实例
//
//        val c: Call = httpClient.newCall(httpRequest)
//        val res: Response = c.execute()
//        Log.i("CreateTemporarySignature", "\tStatus:" + res.code)
//        if (res.body != null) {
//            Log.i("CreateTemporarySignature", "\tContent:" + res.body!!.string() + "\n")
//        }
//        res.close()


    }
}